import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class SendRoutine3 extends Thread {

	private File sendingFolder = new File(PrefProperties3.workingDirectory+"/.to-send/");
	private Client cl;

	public SendRoutine3() {

	}

	public void run() {
		try {
			while (true) {
				System.out.println("Searching file to send ...");
				fileListing();
				Thread.sleep(10000);
			}
		} catch (Exception e) {
		}
	}

	private void fileListing() throws IOException {
		try {
			for (final File fileEntry : sendingFolder.listFiles()) {
				
				//System.out.println("CLIENT - "+fileEntry.getName()+" will be sent.");
				if(!PrefProperties3.demoMode){
					randomSend(fileEntry);
				}
				
			}
		} catch (NullPointerException ex) {
			System.out.println("Folder path not found !");
			if(!sendingFolder.exists())
				sendingFolder.mkdir();
		}
	}
	
	public void randomSend(File f)
	{
			final File fileEntry = f;
			int random = PrefProperties3.myInputPort;
			while(random == PrefProperties3.myInputPort)
				random = (int)(Math.random() * ((PrefProperties3.inputPortMax+1)-PrefProperties3.inputPortMin)) + PrefProperties3.inputPortMin;
			
			System.out.println("CLIENT - Choosen port : "+random);
			cl=new Client(new Callback(){
				@Override
				public void callback() {
					System.out.println("CLIENT - file has been sent to.");
				}}, new FileObject(PrefProperties3.login,0,fileEntry.getAbsolutePath()),"localhost", random);
			
			cl.run();
	}
	
	public byte[] read(File file) throws IOException {

		FileInputStream fileInputStream=null;
 
        byte[] bFile = new byte[(int) file.length()];
 
        try {
            //convert file into array of bytes
	    fileInputStream = new FileInputStream(file);
	    fileInputStream.read(bFile);
	    fileInputStream.close();
 
        }catch(Exception e){
        	e.printStackTrace();
        }
        return bFile;
    }
}